import { api, uploadFile } from '@/utils/request.js'
import config from '@/utils/config.js'

const state = {
  albums: [],
  photos: [],
  currentAlbum: null
}

const mutations = {
  SET_ALBUMS(state, albums) {
    state.albums = albums
  },
  ADD_ALBUM(state, album) {
    state.albums.push(album)
  },
  REMOVE_ALBUM(state, albumId) {
    state.albums = state.albums.filter(album => album.id !== albumId)
  },
  SET_PHOTOS(state, photos) {
    state.photos = photos
  },
  ADD_PHOTO(state, photo) {
    state.photos.push(photo)
  },
  REMOVE_PHOTO(state, photoId) {
    state.photos = state.photos.filter(photo => photo.id !== photoId)
  },
  SET_CURRENT_ALBUM(state, album) {
    state.currentAlbum = album
  }
}

const actions = {
  async fetchAlbums({ commit }) {
    try {
      console.log('开始获取相册列表...')
      const response = await api.get('/albums')
      console.log('相册API响应:', response)
      console.log('相册数据:', response.data)
      
      const albums = response.data || []
      console.log('设置相册数据到store:', albums)
      commit('SET_ALBUMS', albums)
      
      return albums
    } catch (error) {
      console.error('获取相册列表失败:', error)
      throw error
    }
  },

  async createAlbum({ commit }, albumData) {
    try {
      const response = await api.post('/albums', albumData)
      commit('ADD_ALBUM', response.data)
      return response.data
    } catch (error) {
      console.error('创建相册失败:', error)
      throw error
    }
  },

  async fetchPhotos({ commit }, albumId) {
    if (!albumId || isNaN(albumId)) {
      console.error('fetchPhotos called with invalid albumId:', albumId);
      return;
    }
    try {
      const response = await api.get(`/albums/${albumId}/photos`)
      commit('SET_PHOTOS', response.data || [])
    } catch (error) {
      console.error('获取照片列表失败:', error)
    }
  },
  
  async fetchAlbumDetails({ commit, state, dispatch }, albumId) {
      // Find album from existing list. If not found, fetch all albums.
      let album = state.albums.find(a => a.id === albumId);
      if (album) {
          commit('SET_CURRENT_ALBUM', album);
      } else {
          // Ideally you'd have a /album/{id} endpoint, this is a fallback
          console.warn("Could not find album in state, refetching all.");
          await dispatch('fetchAlbums');
          album = state.albums.find(a => a.id === albumId);
          if (album) {
             commit('SET_CURRENT_ALBUM', album);
          }
      }
  },

  async uploadPhoto({ dispatch }, { albumId, filePath }) {
    try {
      const response = await uploadFile({
        url: '/photo/upload', // 特定于相册照片的上传接口
        filePath: filePath,
        name: 'file',
        formData: {
          albumId: albumId,
          description: ''
        }
      });
      // uploadFile 返回的是完整的后端响应体, photo DTO 在 data 字段中
      return response.data; 
    } catch (error) {
      console.error('上传照片失败:', error);
      throw error;
    }
  },
  
  async addPhotoRecord({ commit }, photoData) {
      const response = await api.post('/photo/add', photoData);
      commit('ADD_PHOTO', response.data);
  },

  async deleteAlbum({ commit }, albumId) {
    try {
      await api.delete(`/albums/${albumId}`)
      commit('REMOVE_ALBUM', albumId)
    } catch (error) {
      console.error('删除相册失败:', error)
      throw error
    }
  },

  async deletePhoto({ commit }, photoId) {
    try {
      await api.delete(`/photo/${photoId}`)
      commit('REMOVE_PHOTO', photoId)
    } catch (error) {
      console.error('删除照片失败:', error)
      throw error
    }
  },

  async updateAlbumCover({ commit, state }, { albumId, coverUrl }) {
    try {
      const response = await api.put(`/albums/${albumId}/cover`, { coverUrl })
      
      // 更新当前相册信息
      if (state.currentAlbum && state.currentAlbum.id === albumId) {
        commit('SET_CURRENT_ALBUM', response.data)
      }
      
      // 更新相册列表中的相册信息
      const albums = state.albums.map(album => 
        album.id === albumId ? { ...album, coverUrl } : album
      )
      commit('SET_ALBUMS', albums)
      
      return response.data
    } catch (error) {
      console.error('更新相册封面失败:', error)
      throw error
    }
  }
}

const getters = {
  albums: state => state.albums,
  photos: state => state.photos,
  currentAlbum: state => state.currentAlbum
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 
